package com.hxzy.common.aspect;

import cn.hutool.core.util.ReflectUtil;
import com.alibaba.fastjson.serializer.ValueFilter;
import com.hxzy.common.annon.LogSensitive;
import com.hxzy.common.enums.SensitiveEnum;
import lombok.extern.log4j.Log4j2;
import org.springframework.util.ObjectUtils;

import java.lang.reflect.Field;

/**
 * 重写fastjson序列化规则
 *
 * @author tonneyyy
 */
public class LogSenstiveFastJsonFilter  implements ValueFilter {


    @Override
    public Object process(Object object, String name, Object value) {
        if (ObjectUtils.isEmpty(value) || !(value instanceof String)) {
            return value;
        }


            Field field = ReflectUtil.getField(object.getClass(), name);
            //Field field = object.getClass().getDeclaredField(name);
            //如果字段不存在，理论上是不可能的
            if(field!=null){
                LogSensitive sensitiveInfo = field.getAnnotation(LogSensitive.class);
                //如果注解不存在，或者字段类型不是字符串
                if (String.class != field.getType() || ObjectUtils.isEmpty(sensitiveInfo)) {
                    return value;
                }

                //得到原始的值
                String originVal = String.valueOf(value);
                //得到注解上面的枚举
                SensitiveEnum  sensitiveEnum = sensitiveInfo.type();
                String newValue= SensitiveSerialize.desensitized(originVal,sensitiveEnum);
                return newValue;
            }else{

              return value;
            }
    }
}
